const app = getApp();
const md5 = require('./md5.js');
const base64 = require('./base64.js');
let config = {
    oid: 18,
    brand_code: 'kd',
    host: 'https://www.zjsuichong.com/min/ali',
    qrcodeurl: 'https://www.zjsuichong.com', //二维码链接地址
    headerkey: '',
}

/**
 * 解密
 * @param  string $data 需要解密的数据
 * @param  string $key  密码
 * @return string       解密后的数据
 */
function mwdecrypt(data, key = 'xfz61281006') {
    key = md5.hexMD5(key)
    var x = 0,
        data = base64.base64decode(data),
        len = data.length,
        l = key.length,
        char = '',
        str = ''
    for (var i = 0; i < len; i++) {
        if (x == l) {
            x = 0
        }
        char += key.substr(x, 1)
        x++
    }
    for (var i = 0; i < len; i++) {
        if ((data.substr(i, 1)).charCodeAt() < (char.substr(i, 1)).charCodeAt()) {
            str += String.fromCharCode(((data.substr(i, 1)) + 256).charCodeAt() - (char.substr(i, 1)).charCodeAt())
        } else {
            str += String.fromCharCode((data.substr(i, 1).charCodeAt()) - (char.substr(i, 1)).charCodeAt())
        }
    }
    return str
}


// 请求后台接口（封装my.request）
function httpRequest(url, params, successCallback, canCallback = function () {
}) {
    my.request({
        url: config.host + url,
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'openid': app.globalData.openID,
            'brand-code': config.brand_code,
            'client': 'ali'
        },
        data: params,
        dataType: 'json',
        success: function (res) {
            if (!res.data) {
                canCallback()
                my.showToast({
                    content: '系统繁忙',
                    type: 'none'
                });
            }
            switch (res.data.code) {
                case 0:
                    canCallback();
                    my.showToast({
                        content: res.data.msg,
                        type: 'none'
                    });
                    break;
                case 401:
                    canCallback()
                    my.showToast({
                        content: '未登录/未授权',
                        type: 'none'
                    });
                    break;
                case 403:
                    canCallback()
                    my.showToast({
                        content: '非法请求',
                        type: 'none'
                    });
                    break;
                default:
                    successCallback(res.data)
                    break;
            }
        },
        fail: function (res) {
            canCallback()
            my.showToast({
                content: '系统繁忙',
                type: 'none'
            });
        }
    });
}

// 获取用户信息
function getUserInfoAlipay(callback) {
    my.getLocation({
        success(res) {
            app.globalData.longitude = res.longitude;
            app.globalData.latitude = res.latitude;
        }
    });
    my.getAuthCode({
        scopes: 'auth_user',
        success: (res) => {
            my.getAuthUserInfo({
                success: (res) => {
                    callback(res);
                }
            });
        },
    });
}

// 支付宝支付
function alipayPayment(amount, type, sn, extra, successCallback, completeCallback) {
    httpRequest('/alipayRecharge', {
        amount: amount,
        type: type,
        sn: sn,
        extra: extra
    }, function (res) {
        if (res.code == 1) {
            let payments = res.data;
            my.tradePay({
                tradeNO: payments.trade_no.toString(),
                success: function (paysuccess) {
                    // console.log(paysuccess)
                    if (paysuccess.resultCode == 9000) {
                        successCallback(res.data.order_id)
                    } else if (paysuccess.resultCode == 8000) {
                        my.showToast({
                            content: '正在处理中',
                            type: 'success'
                        });
                    } else if (paysuccess.resultCode == 6004) {
                        my.showToast({
                            content: '支付结果未知，请查询商户订单列表中订单的支付状态'
                        });
                    } else if (paysuccess.resultCode == 6002) {
                        my.showToast({
                            content: '网络连接出错'
                        });
                    } else if (paysuccess.resultCode == 6001) {
                        my.showToast({
                            content: '您取消了支付'
                        });
                    } else {
                        my.showToast({
                            content: '支付未完成',
                            type: 'none'
                        });
                    }
                },
                fail: function (fail) {
                    my.showToast({
                        content: '支付未完成',
                        type: 'none'
                    });
                },
                complete: function (res) {
                    completeCallback()
                }
            })
        } else {
            completeCallback();
            my.showToast({
                content: '支付失败',
                type: 'none'
            });
        }
    })
}


function alipayFreeze(amount, sn, successCallback, completeCallback) {
    httpRequest('/doFreeze', {
        sn: sn,
        amount: amount
    }, function (res) {
        if (res.code == 1) {
            let payments = res.data.params.body;
            my.tradePay({
                orderStr: payments,
                success: function (paysuccess) {
                    if (paysuccess.resultCode == 9000) {
                        successCallback(res.data.used_id)
                    } else if (paysuccess.resultCode == 8000) {
                        my.showToast({
                            content: '正在处理中',
                            type: 'success'
                        });
                    } else if (paysuccess.resultCode == 6004) {
                        my.showToast({
                            content: '支付结果未知，请查询商户订单列表中订单的支付状态'
                        });
                    } else if (paysuccess.resultCode == 6002) {
                        my.showToast({
                            content: '网络连接出错'
                        });
                    } else if (paysuccess.resultCode == 6001) {
                        my.showToast({
                            content: '用户中途取消'
                        });
                    } else {
                        my.showToast({
                            content: '支付未完成',
                            type: 'none'
                        });
                    }
                },
                fail: function (fail) {
                    my.showToast({
                        content: '支付未完成',
                        type: 'none'
                    });
                },
                complete: function (res) {
                    completeCallback()
                }
            })
        } else {
            completeCallback();
            my.showToast({
                content: '支付失败',
                type: 'none'
            });
        }
    })
}


function cabinet(link, blength) {
    let oidlength = null;
    let oid = null;
    let qrcode = null;
    if (link.indexOf('&&cineda=') != -1) {
        oidlength = link.indexOf('&&cineda=');
        oid = link.substring(blength, oidlength);
        oid = mwdecrypt(oid);
        qrcode = link.substring(oidlength + 9);
    } else if (link.indexOf('&&t=') != -1) {
        oidlength = link.indexOf('&&t=');
        oid = link.substring(blength, oidlength);
        oid = mwdecrypt(oid);
        qrcode = link.substring(oidlength + 4);
    }
    return {oid: oid, type: 'cab', qrcode: qrcode}
}

function lineCharging(link, blength) {
    let oidlength = link.indexOf('&&t=');
    let oid = link.substring(blength, oidlength);
    oid = mwdecrypt(oid);
    let qrcode = link.substring(oidlength + 4);
    return {oid: oid, type: 'line', qrcode: qrcode}
}

module.exports = {
    config: config,
    mwdecrypt: mwdecrypt,
    httpRequest: httpRequest,
    getUserInfoAlipay: getUserInfoAlipay,
    alipayPayment: alipayPayment,
    alipayFreeze: alipayFreeze
}
